package com.powerunion.datacollection.service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;

import com.powerunion.datacollection.common.Constants;
import com.powerunion.datacollection.common.SystemException;
import com.powerunion.datacollection.dao.DaoException;
import com.powerunion.datacollection.dao.DaoFactory;
import com.powerunion.datacollection.dao.DataCollectViewDao;
import com.powerunion.datacollection.dao.TargetDao;
import com.powerunion.datacollection.dao.TargetFieldsDao;
import com.powerunion.datacollection.dao.impl.TargetDaoImpl;
import com.powerunion.datacollection.dao.impl.TargetFieldsDaoImpl;
import com.powerunion.datacollection.model.Column;
import com.powerunion.datacollection.model.GlobalTargetsData;
import com.powerunion.datacollection.model.Target;
import com.powerunion.datacollection.model.TargetFields;
import com.powerunion.datacollection.model.jsonObject.GlobalTargetsDataJSONObject;
import com.powerunion.datacollection.model.jsonObject.GlobalTargetsDataListVO;
import com.powerunion.datacollection.model.jsonObject.GlobalTargetsDataVO;
import com.powerunion.datacollection.model.jsonObject.GroupHeader;
import com.powerunion.datacollection.model.jsonObject.JSONDataBean;
import com.powerunion.util.log.LogHelper;

public class DataCollectViewManager {
	private static Logger logger = LogHelper.getInstance().getLogger(
			DataCollectViewManager.class);
	private DataCollectViewDao dao = null;

	public DataCollectViewManager() {
		super();
		this.dao = (DataCollectViewDao) DaoFactory.getInstance().getDao(
				DataCollectViewDao.class);
	}

	public List getTargetsCategoryByFormId(String formId) throws Exception {
		return this.dao.getTargetCategorys(formId);
	}

	public List getTargetDataCollectByAct(String procId, String actId,
			String categoryId, int flag) throws Exception {
		// 参数为空
		if (StringUtils.isEmpty(actId)) {
			String[] args = { "actId" };
			// 打印错误日志
			StringBuffer msglog = new StringBuffer(
					"empty invoke parameter actId NULL ");
			logger.error(msglog.toString());
			throw new SystemException("error.common.parameter.empty", args);
		}

		List groupHeads = this.dao.getGroupHeadByAct(procId, actId, flag);

		List leaves = new ArrayList();
		getLeaves(groupHeads, leaves);

		if (leaves.size() > 0) {
			GroupHeader header = (GroupHeader) leaves.get(0);

			ColumnManager cm = new ColumnManager();
			List columns = cm.getColumnsByFormId(header.getFormId());
			if (columns.size() > 0)
				columns.remove(0);

			List targetdatas = this.dao.getTargetDataCollectByGroupHeaders(
					leaves, categoryId);

			TargetDao td = new TargetDaoImpl();
			List tList = td.findTargets(categoryId);

			// 这里的datas中包含指标分类
			int gh = targetdatas.size();
			int targetCount = tList.size();

			List datas = new ArrayList();

			int row = columns.size();
			int count = targetCount * row;

			// 前两列
			for (int i = 0; i < count; i++) {
				List rowdata = new ArrayList();
				if (i % row == 0) {
					int k = i / row;
					Target t = (Target) tList.get(k);
					rowdata.add(t.getTargetName());
				} else
					rowdata.add(""); // 指标
				int j = i % row;
				Column col = (Column) columns.get(j);
				rowdata.add(col.getHeader());
				datas.add(rowdata);
			}

			TargetFieldsDao tfd = new TargetFieldsDaoImpl();
			List fList = tfd.getTargetFields(categoryId);

			// 处理个指标数据
			for (int i = 0; i < gh; i++) {
				List l = (List) targetdatas.get(i); // 表头对应的所有指标数据
				for (int j = 0; j < targetCount; j++) {
					GlobalTargetsData gtd = (GlobalTargetsData) l.get(j);
					for (int k = 0; k < row; k++) {
						TargetFields targetFields = (TargetFields) fList.get(k);
						String value = BeanUtils.getProperty(gtd, targetFields
								.getFieldName());
						List lk = (List) datas.get(j * row + k);
						lk.add(value);
					}
				}
			}

			return datas;

		}

		return null;

	}

	private void getLeaves(List groupHeads, List leaves) {

		if (groupHeads != null) {
			for (int i = 0; i < groupHeads.size(); i++) {
				GroupHeader header = (GroupHeader) groupHeads.get(i);
				if (header.getChildren() == null)
					leaves.add(header);
				else if (header.getChildren().size() == 0)
					leaves.add(header);
				else
					getLeaves(header.getChildren(), leaves);
			}
		}
	}

	/**
	 * 
	 * @param procId
	 * @param actId
	 * @param subDataOrCollectData
	 *            标识 是取当前上报任务的数据还是汇总的数据
	 * @return
	 * @throws Exception
	 */
	public String getGroupHeadByAct(String procId, String actId,
			int subDataOrCollectData) throws Exception {
		// 参数为空
		if (StringUtils.isEmpty(procId)) {
			String[] args = { "procId" };
			// 打印错误日志
			StringBuffer msglog = new StringBuffer(
					"empty invoke parameter procId NULL ");
			logger.error(msglog.toString());
			throw new SystemException("error.common.parameter.empty", args);
		}
		// 参数为空
		if (StringUtils.isEmpty(actId)) {
			String[] args = { "actId" };
			// 打印错误日志
			StringBuffer msglog = new StringBuffer(
					"empty invoke parameter actId NULL ");
			logger.error(msglog.toString());
			throw new SystemException("error.common.parameter.empty", args);
		}
		List groupHeads = this.dao.getGroupHeadByAct(procId, actId,
				subDataOrCollectData);
		JSONArray jsonArr = JSONArray.fromObject(groupHeads);
		String result = "{results:" + jsonArr + "}";
		return result;
	}

	public List getGroupHeadListByAct(String procId, String actId,
			int subDataOrCollectData) throws Exception {
		// 参数为空
		if (StringUtils.isEmpty(procId)) {
			String[] args = { "procId" };
			// 打印错误日志
			StringBuffer msglog = new StringBuffer(
					"empty invoke parameter procId NULL ");
			logger.error(msglog.toString());
			throw new SystemException("error.common.parameter.empty", args);
		}
		// 参数为空
		if (StringUtils.isEmpty(actId)) {
			String[] args = { "actId" };
			// 打印错误日志
			StringBuffer msglog = new StringBuffer(
					"empty invoke parameter actId NULL ");
			logger.error(msglog.toString());
			throw new SystemException("error.common.parameter.empty", args);
		}
		return this.dao.getGroupHeadByAct(procId, actId, subDataOrCollectData);

	}

	/**
	 * 获取所有的报送数据
	 * 
	 * @param documentId
	 * @param procId
	 * @return
	 * @throws Exception
	 */
	public List getTemplateData(String documentId, String procId, String actId)
			throws Exception {
		// 参数为空
		if (StringUtils.isEmpty(documentId)) {
			String[] args = { "documentId" };
			// 打印错误日志
			StringBuffer msglog = new StringBuffer(
					"empty invoke parameter documentId NULL ");
			logger.error(msglog.toString());
			throw new SystemException("error.common.parameter.empty", args);
		}
		SubmissionWorkItemManager swm = new SubmissionWorkItemManager();
		List submissionWorkItems = swm.getAllSubWorksByAct(procId, actId, Constants.DATACOLLECTVIEW_REQUEST_TYPE_COLLECT);

		return this.dao
				.getTemplateData(documentId, procId, submissionWorkItems);
	}

	/**
	 * 获取当前的审批任务的数据
	 * 
	 * @param documentId
	 *            表单id
	 * @param procId
	 *            流程实例id
	 * @param actId
	 *            步骤Id
	 * @param approveId
	 *            当前的审批任务
	 * @return
	 * @throws Exception
	 */
	public List getTemplateDataByActId(String documentId, String procId,
			String actId, String approveId) throws Exception {
		// 参数为空
		if (StringUtils.isEmpty(documentId)) {
			String[] args = { "documentId" };
			// 打印错误日志
			StringBuffer msglog = new StringBuffer(
					"empty invoke parameter documentId NULL ");
			logger.error(msglog.toString());
			throw new SystemException("error.common.parameter.empty", args);
		}

		return this.dao.getTemplateDataByActId(documentId, procId, actId,
				approveId);
	}
	
	public boolean save(String saveStr,String actId,String procId,String updateUser,int currentOrParrent,int actType)
		throws Exception {
		// 参数为空
		if (StringUtils.isEmpty(saveStr)) {
			String[] args = { "saveStr" };
			// 打印错误日志
			StringBuffer msglog = new StringBuffer(
					"empty invoke parameter saveStr NULL ");
			logger.error(msglog.toString());
			throw new SystemException("error.common.parameter.empty", args);
		}
		
		// 参数为空
		if (StringUtils.isEmpty(actId)) {
			String[] args = { "actId" };
			// 打印错误日志
			StringBuffer msglog = new StringBuffer(
					"empty invoke parameter actId NULL ");
			logger.error(msglog.toString());
			throw new SystemException("error.common.parameter.empty", args);
		}
		
		// 参数为空
		if (StringUtils.isEmpty(procId)) {
			String[] args = { "procId" };
			// 打印错误日志
			StringBuffer msglog = new StringBuffer(
					"empty invoke parameter procId NULL ");
			logger.error(msglog.toString());
			throw new SystemException("error.common.parameter.empty", args);
		}
		
		// 参数为空
		if (StringUtils.isEmpty(updateUser)) {
			String[] args = { "updateUser" };
			// 打印错误日志
			StringBuffer msglog = new StringBuffer(
					"empty invoke parameter updateUser NULL ");
			logger.error(msglog.toString());
			throw new SystemException("error.common.parameter.empty", args);
		}

		Map gMap = new HashMap();
		gMap.put("data", GlobalTargetsDataListVO.class);
		gMap.put("targets", GlobalTargetsDataVO.class);
		JSONDataBean am = (JSONDataBean)JSONObject.toBean(JSONObject.fromObject(saveStr), JSONDataBean.class,gMap);
		List list = am.getData();
		boolean flag = false;
		if(!list.isEmpty()){
			flag = this.dao.save(list, updateUser, procId, actId, currentOrParrent,actType);
		}
		
		return flag;
	}
	


	// public List getTemplateData(String documentId) throws Exception{
	// // 参数为空
	// if (StringUtils.isEmpty(documentId)) {
	// String[] args = { "documentId" };
	// // 打印错误日志
	// StringBuffer msglog = new StringBuffer(
	// "empty invoke parameter documentId NULL ");
	// logger.error(msglog.toString());
	// throw new SystemException("error.common.parameter.empty", args);
	// }
	//		
	// return this.dao.getTemplateData(documentId);
	//	}

}
